package com.anosine.gpsl.android.ui.activity;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import android.view.ViewGroup.LayoutParams;

import com.anosine.gpsl.android.AppConstants;
import com.anosine.gpsl.android.GPSLApp;
import com.anosine.gpsl.android.R;
import com.anosine.gpsl.android.WebConstants;
import com.anosine.gpsl.android.base.BaseActivity;
import com.anosine.gpsl.android.base.BaseFragment;
import com.anosine.gpsl.android.entity.Active;
import com.anosine.gpsl.android.entity.ActiveList;
import com.anosine.gpsl.android.entity.Login;
import com.anosine.gpsl.android.entity.UpdataInfoBean;
import com.anosine.gpsl.android.entity.UpdateBean;
import com.anosine.gpsl.android.presenter.ActivieListPresenter;
import com.anosine.gpsl.android.ui.ActiveListView;
import com.anosine.gpsl.android.ui.fragment.TabFortifiedFragment;
import com.anosine.gpsl.android.ui.fragment.TabMessageFragment;
import com.anosine.gpsl.android.ui.fragment.TabMineFragment;
import com.anosine.gpsl.android.ui.fragment.TabMonitoringFragmentNew;
import com.anosine.gpsl.android.util.ActivityFrgManager;
import com.anosine.gpsl.android.util.HttpRequestListener;
import com.anosine.gpsl.android.util.SendHttpUtils;
import com.anosine.gpsl.android.util.ShakeListener;
import com.anosine.gpsl.android.util.ShakeListener.OnShakeListener;
import com.anosine.gpsl.android.util.ShowConfirmDlgA;
import com.anosine.gpsl.android.util.ShowDownloadProgressDlgA;
import com.anosine.gpsl.android.util.ToastHelper;
import com.anosine.gpsl.android.util.UserInfoProxy;
import com.anosine.gpsl.android.util.common;
import com.anosine.gpsl.android.widget.MyWindowManager;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.http.RequestParams;

import android.app.ActivityManager;
import android.app.ProgressDialog;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.app.FragmentTransaction;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * @Title: MainActivity
 * @Package com.anosine.gpsl.android.ui.activity
 * @Description: main界面
 * @author: sunny
 * @date: 2015-11-23
 * @version V1.0
 */

public class GPSLMainActivity extends BaseActivity implements
		View.OnClickListener, ActiveListView {
	private static final int TAG_FRGMENT_SIZE = 4;
	private boolean isShowExitTip = false;

	public TextView mBtnView[];
	// private Spinner mBtnSpinner;
	private int mSelectPosition = -1;
	private BaseFragment mCurrentShowFrg;

	private static GPSLMainActivity sActivity;
	public static String sAlarmState;
	public RelativeLayout passThrough;
	private TextView message;
	private myreceiver receiver;
	ImageView close;
	ShakeListener mShakeListener = null;

	/**
	 * 方法名：onBaseCreate(Bundle savedInstanceState) 功 能：初始化 参 数：Bundle
	 * savedInstanceState Activity结束前，如果需要保存状态，
	 * 就在onsaveInstanceState中，将状态数据以key-value的形式放入到savedInstanceState中。
	 * 这样，当一个Activity被创建时，就能从onCreate的参数savedInsanceState中获得状态数据
	 * 
	 * @return 无
	 * */
	@Override
	protected void onBaseCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_main);
		// ///////////////////////////
		ActivieListPresenter presenter = new ActivieListPresenter(this);
		Login userInfo = UserInfoProxy.getInstance().getLoginInfo();
		presenter.loadActiveList(userInfo.getObjectid(), userInfo.userMd5);
		// ///////////////////////
		sActivity = this;
		receiver = new myreceiver();
		// IntentFilter filter = new IntentFilter();
		// filter.addAction("PushPassThrough");
		// filter.addAction("OperateFalse");
		// filter.addAction("OperateTrue");
		// registerReceiver(receiver, filter);
		String mess = GPSLApp.getMessage();
		// 自动检测是否更新
//		Intent intent = getIntent();
//		String StringE = intent.getStringExtra("isShowTabMessage");
//		if ("ShowTabMessage".equals(StringE)) {
//			mSelectPosition = 2;
//		} else {
//			mSelectPosition = -1;
//		}
//		if (TabMonitoringFragmentNew.isPlayer == 0) {
//		} else if (TabMonitoringFragmentNew.isPlayer == 1) {
//			TabMonitoringFragmentNew.player.stop();
//		}
		clickBtnUpdate();
		passThrough = (RelativeLayout) findViewById(R.id.passThrough);
		message = (TextView) findViewById(R.id.message);
		close = (ImageView) findViewById(R.id.close);
		close.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				passThrough.setVisibility(View.GONE);
			}
		});
		initView();
		// 报警跳转接收

		mShakeListener = new ShakeListener(GPSLMainActivity.this);
		mShakeListener.setOnShakeListener(new OnShakeListener() {
			public void onShake() {
				// 当前界面是桌面，且没有悬浮窗显示，则创建悬浮窗。

				if (isHome() && !MyWindowManager.isWindowShowing()) {

					MyWindowManager.isShowSetWindow = false;
					MyWindowManager.createSmallWindow(GPSLMainActivity.this
							.getApplicationContext());
					new Handler().postDelayed(new Runnable() {
						public void run() {
							if (MyWindowManager.isFirst) {
								new Handler().postDelayed(new Runnable() {
									public void run() {
										MyWindowManager
												.removeSmallWindow(GPSLMainActivity.this
														.getApplicationContext());
									}
								}, 1000);
								MyWindowManager.isFirst = true;
							}
						}
					}, 4000);

				}

			}
		});
		
		llheight=(LinearLayout)findViewById(R.id.llheight);
	}
	LinearLayout llheight;
	/**
	 * 判断当前界面是否是桌面
	 */
	private boolean isHome() {
		ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> rti = mActivityManager.getRunningTasks(1);
		String nowPkg = getCurrentPkgName(this);
		List<String> strs = getHomes();
		if (strs != null && strs.size() > 0) {
			return strs.contains(nowPkg);
		} else {
			return false;
		}
	}

	public static String getCurrentPkgName(Context context) {
		ActivityManager.RunningAppProcessInfo currentInfo = null;
		Field field = null;
		int START_TASK_TO_FRONT = 2;
		String pkgName = null;
		try {
			field = ActivityManager.RunningAppProcessInfo.class
					.getDeclaredField("processState");
		} catch (Exception e) {
			e.printStackTrace();
		}
		ActivityManager am = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningAppProcessInfo> appList = am.getRunningAppProcesses();
		for (ActivityManager.RunningAppProcessInfo app : appList) {
			if (app.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
				Integer state = null;
				try {
					state = field.getInt(app);
				} catch (Exception e) {
					e.printStackTrace();
				}
				if (state != null && state == START_TASK_TO_FRONT) {
					currentInfo = app;
					break;
				}
			}
		}
		if (currentInfo != null) {
			pkgName = currentInfo.processName;
		}
		return pkgName;
	}
	
	/**
	 * 获得属于桌面的应用的应用包名称
	 * 
	 * @return 返回包含所有包名的字符串列表
	 */
	private List<String> getHomes() {
		List<String> names = new ArrayList<String>();
		PackageManager packageManager = this.getPackageManager();
		Intent intent = new Intent(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_HOME);
		// 返回给定条件的所有ResolveInfo对象(本质上是Activity)，集合对象 queryIntentActivities
		List<ResolveInfo> resolveInfo = packageManager.queryIntentActivities(
				intent, 0);// PackageManager.MATCH_DEFAULT_ONLY
		names.clear();
		for (ResolveInfo ri : resolveInfo) {
			names.add(ri.activityInfo.packageName);
		}

		return names;
	}

	private class myreceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction() == "PushPassThrough") {
				String gMessage = intent.getStringExtra("message");
				passThrough.setVisibility(View.VISIBLE);
				message.setText(gMessage);
			} else if (intent.getAction() == "OperateFalse") {
				new Handler().postDelayed(new Runnable() {
					public void run() {
						MyWindowManager.removeSmallWindow(GPSLMainActivity.this
								.getApplicationContext());
						MyWindowManager.isFirst = true;
					}
				}, 5000);
			} else if (intent.getAction() == "OperateTrue") {
				if (MyWindowManager.isShowSetWindow) {
					MyWindowManager.isFirst = false;
				} else {
					MyWindowManager.isFirst = true;
					new Handler().postDelayed(new Runnable() {
						public void run() {
							MyWindowManager
									.removeSmallWindow(GPSLMainActivity.this
											.getApplicationContext());
							MyWindowManager.isFirst = true;
						}
					}, 5000);
				}

			} else {
				finish();
			}

		}

	}

	/**
	 * 方法名：getMetaValue(Context context, String metaKey) 功 能：获取ApiKey
	 * 
	 * @param Context
	 *            context 上下文
	 * @param String
	 *            metaKey 百度推送的api key
	 * @return String apiKey
	 * */
	public static String getMetaValue(Context context, String metaKey) {
		Bundle metaData = null;
		String apiKey = null;
		if (context == null || metaKey == null) {
			return null;
		}
		try {
			ApplicationInfo ai = context.getPackageManager()
					.getApplicationInfo(context.getPackageName(),
							PackageManager.GET_META_DATA);
			if (null != ai) {
				metaData = ai.metaData;
			}
			if (null != metaData) {
				apiKey = metaData.getString(metaKey);
			}
		} catch (PackageManager.NameNotFoundException e) {

		}
		return apiKey;
	}

	/**
	 * 方法名：onNewIntent(Intent intent) 功 能：初始化 参 数：Intent intent
	 * 
	 * @return none
	 * */
	// @Override
	// protected void onNewIntent(Intent intent) {
	// super.onNewIntent(intent);
	// onBaseCreate(null);
	// }

	/**
	 * 方法名：initViews() 功 能：初始化view,继承的方法 参 数：无
	 * 
	 * @return none
	 * */
	@Override
	protected void initViews() {

	}

	Login info;

	/**
	 * 方法名：initView() 功 能：初始化view 参 数：无
	 * 
	 * @return none
	 * */
	private void initView() {
		mBtnView = new TextView[TAG_FRGMENT_SIZE];
		for (int i = 1; i < mBtnView.length; i++) {
			mBtnView[i] = (TextView) findViewById(R.id.tv_btn1 + i);
			mBtnView[i].setOnClickListener(this);
		}
		mBtnView[0] = (TextView) findViewById(R.id.tv_btn1);
		// mBtnSpinner = (Spinner) findViewById(R.id.tv_btn1);
		info = UserInfoProxy.getInstance().getLoginInfo();

	}

	/**
	 * 方法名：initDataSelectPosition(int position) 功 能：初始化被选中的位置数据 参 数：int position
	 * 位置
	 * 
	 * @return none
	 * */
	public void initDataSelectPosition(int position) {
		if (mSelectPosition == position) {
			return;
		} else {
			mSelectPosition = position;
		}
		initFrgsAndShow();
		resetSelectBtnBg();
	}

	ArrayAdapter<String> adapter;

	/**
	 * 方法名：initFrgsAndShow() 功 能：初始化并显示fragment 参 数：无
	 * 
	 * @return none
	 * */
	private void initFrgsAndShow() {
		if (mSelectPosition < 0 || mSelectPosition > TAG_FRGMENT_SIZE) {
			throw new IllegalStateException("position error");
		}
		switch (mSelectPosition) {
		case 0:
			mCurrentShowFrg = new TabMonitoringFragmentNew();
			Bundle bundle = new Bundle();

			if (info.SaveOid == null) {
				bundle.putString("oid", mActive.get(0).oid);
			} else {
				boolean isExist = false;
				for (int i = 0; i < mActive.size(); i++) {
					if (info.SaveOid.equals(mActive.get(i).oid)) {
						isExist = true;
						break;
					}
				}
				if (isExist) {
					bundle.putString("oid", info.SaveOid);
				} else {
					bundle.putString("oid", mActive.get(0).oid);
				}

			}
			mCurrentShowFrg.setArguments(bundle);
			break;
		case 1:
			mCurrentShowFrg = new TabFortifiedFragment();

			break;
		case 2:
			mCurrentShowFrg = new TabMessageFragment();

			break;
		case 3:
			mCurrentShowFrg = new TabMineFragment();

			break;

		}

		FragmentTransaction mTransaction = getSupportFragmentManager()
				.beginTransaction();
		mTransaction.setCustomAnimations(R.anim.slide_in_from_left, 0);
		mTransaction.replace(R.id.area_show_content, mCurrentShowFrg);
		mTransaction.commit();
	}

	/**
	 * 方法名：onDestroy() 功 能：销毁 参 数：无
	 * 
	 * @return none
	 * */
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mShakeListener != null) {
			mShakeListener.stop();
		}
		sActivity = null;
	}

	/**
	 * 方法名：getMainInstance() 功 能：获取MainActivity上下文 参 数：无
	 * 
	 * @return MainActivity
	 * */
	public static GPSLMainActivity getMainInstance() {
		return sActivity;
	}

	/**
	 * 方法名：refreshDataShow() 功 能：刷新数据显示 参 数：无
	 * 
	 * @return 无
	 * */
	public void refreshDataShow() {
		if (mCurrentShowFrg != null
				&& !(mCurrentShowFrg instanceof TabMessageFragment)) {
			mCurrentShowFrg = new TabMessageFragment();
			TabMessageFragment frg = (TabMessageFragment) mCurrentShowFrg;
			frg.showData();
		}
	}

	/**
	 * 方法名：resetSelectBtnBg() 功 能：重置选择的Button背景 参 数：无
	 * 
	 * @return 无
	 * */
	private void resetSelectBtnBg() {

		for (int i = 1; i < mBtnView.length; i++) {
			if (mSelectPosition == i) {
				mBtnView[i].setTextColor(getResources().getColor(
						R.color.blue_main_light));
				mBtnView[i]
						.setBackgroundResource(R.color.main_head_title_default);
				switch (i) {
				// case 0:
				// mBtnView[i].setCompoundDrawablesWithIntrinsicBounds(0,
				// R.drawable.main_index_checkin_pressed, 0, 0);
				// break;
				case 1:
					mBtnView[i].setCompoundDrawablesWithIntrinsicBounds(0,
							R.drawable.main_index_search_pressed, 0, 0);
					break;
				case 2:
					mBtnView[i].setCompoundDrawablesWithIntrinsicBounds(0,
							R.drawable.main_index_more_pressed, 0, 0);
					break;
				case 3:
					mBtnView[i].setCompoundDrawablesWithIntrinsicBounds(0,
							R.drawable.main_index_my_pressed, 0, 0);
					break;
				}
			} else {
				mBtnView[i]
						.setTextColor(getResources().getColor(R.color.white));
				mBtnView[i]
						.setBackgroundResource(R.color.main_head_title_select);
				switch (i) {
				// case 0:
				// mBtnView[i].setCompoundDrawablesWithIntrinsicBounds(0,
				// R.drawable.main_sign_selector, 0, 0);
				// break;
				case 1:
					mBtnView[i].setCompoundDrawablesWithIntrinsicBounds(0,
							R.drawable.main_search_selector, 0, 0);
					break;
				case 2:
					mBtnView[i].setCompoundDrawablesWithIntrinsicBounds(0,
							R.drawable.main_more_selector, 0, 0);
					break;
				case 3:
					mBtnView[i].setCompoundDrawablesWithIntrinsicBounds(0,
							R.drawable.main_mine_selector, 0, 0);
					break;
				}
			}
		}
	}

	/**
	 * 方法名：onClick(View v) 功 能：onClick点击事件 参 数：View v 被点击的view控件
	 * 
	 * @return 无
	 * */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tv_btn1:
			initDataSelectPosition(0);
			break;
		case R.id.tv_btn2:
			initDataSelectPosition(1);
			break;
		case R.id.tv_btn3:
			initDataSelectPosition(2);
			break;
		case R.id.tv_btn4:
			initDataSelectPosition(3);
			break;
		default:
			break;
		}
	}

	/**
	 * 方法名：onResume() 功 能：activity开始与用户交互时调用（无论是启动还是重新启动一个活动，该方法总是被调用的） 参 数：无
	 * 
	 * @return none
	 * */
	@Override
	protected void onResume() {
		super.onResume();
		ActivityFrgManager.getInstance().clearActivityAdd();
		ActivityFrgManager.getInstance().registerActivity(this);
	}

	/**
	 * 方法名：onBackPressed() 功 能：返回键被触发后进行的事件操作 参 数：无
	 * 
	 * @return none
	 * */
	@Override
	public void onBackPressed() {
		
		if (!isShowExitTip) {
			isShowExitTip = true;
			ToastHelper.toast(this, R.string.app_exit_tip);
			// 此处有问题
			mBtnView[0].postDelayed(new Runnable() {
				@Override
				public void run() {
					isShowExitTip = false;
				}
			}, 2000);
			//用于不重复打开app
			 moveTaskToBack(true);
			return;
		}
		super.onBackPressed();
		finish();
	}

	/**
	 * 方法名：clickBtnUpdate() 功 能：点击更新做的操作 参 数：无 返回值：无
	 */
	@SuppressWarnings("unchecked")
	private void clickBtnUpdate() {
		Login info = UserInfoProxy.getInstance().getLoginInfo();
		if (info != null) {
			showProgressInfo("请求中...");
			RequestParams params = new RequestParams();
			params.addBodyParameter("appid", "201");
			try {
				params.addBodyParameter("version",
						common.getVersionCode(GPSLMainActivity.this) + "");
			} catch (Exception e) {
				e.printStackTrace();
			}
			params.addBodyParameter("platform", "Android");
			SendHttpUtils sendHttp = new SendHttpUtils();
			TypeToken type = new TypeToken<UpdateBean>() {
			};
			String url = String.format("%1s/%2s", AppConstants.sCommonUrl,
					WebConstants.Do_GetServerNewVersion_Action);
			sendHttp.doRequest(url, params, type,
					new HttpRequestListener<UpdateBean>() {

						/**
						 * 方法名：onSuccess(String result, final UpdateBean t) 功
						 * 能：json解析成功后进行的操作 参 数：String result　json数据, final
						 * UpdateBean t　解析后的数据 返回值：无
						 */
						@Override
						public void onSuccess(String result, final UpdateBean t) {
							dismissProgress();
							if (t != null) {
								String version = "1";
								try {
									version = common
											.getVersionCode(GPSLMainActivity.this)
											+ "";
								} catch (Exception e) {
									e.printStackTrace();
								}
								if (("0").equals(t.new_version + "")) {
									// ToastHelper.toast("当前已经是最新版本");
								} else {
									String[] features = null;
									String feature = "";
									if (t.new_version_feature.contains(";")) {
										features = ((String) t.new_version_feature)
												.split(";");
									} else if (t.new_version_feature
											.contains("；")) {
										features = ((String) t.new_version_feature)
												.split("；");
									}

									try {
										for (int i = 0; i < features.length; i++) {
											feature = feature + features[i]
													+ "\n";
										}
									} catch (Exception e) {
										feature = t.new_version_feature;
									}

									final ShowConfirmDlgA dialog = new ShowConfirmDlgA(
											GPSLMainActivity.this, feature,
											"更新提示");
									TextView cancel = dialog.getCancel();
									TextView ok = dialog.getOk();
									ok.setOnClickListener(new OnClickListener() {

										@Override
										public void onClick(View arg0) {
											// TODO Auto-generated method stub
											if (Environment
													.getExternalStorageState()
													.equals(Environment.MEDIA_MOUNTED)) {
												UpdataInfoBean info = new UpdataInfoBean();
												info.setVersion(String
														.valueOf(t.new_version));
												info.setUrl(t.new_version_url);
												info.setDescription(t.new_version_feature
														+ "\n\n");
												downloadApk(info);
												dialog.dismiss();
											} else {
												ToastHelper.toast("请插入SD卡后重试");
											}
										}
									});
									cancel.setOnClickListener(new OnClickListener() {

										@Override
										public void onClick(View arg0) {
											dialog.dismiss();
										}
									});
									dialog.show();

								}

							}
						}

						/**
						 * 方法名：onFailure(String error) 功 能：解析失败或者加载失败后的操作 参
						 * 数：String error　错误信息 返回值：无
						 */
						@Override
						public void onFailure(String error) {
							dismissProgress();
							ToastHelper.toast(error);
						}
					});
		}
	}

	ProgressDialog progressDialogBA;

	/**
	 * 方法名：downloadApk(UpdataInfoBean info) 功 能：下载新的apk 参 数：UpdataInfoBean
	 * info　更新的bean 返回值：无
	 */
	private void downloadApk(final UpdataInfoBean info) {
		final ShowDownloadProgressDlgA dialog = new ShowDownloadProgressDlgA(
				this, info);
		TextView cancel = dialog.getCancel();
		cancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				dialog.dismiss();
			}
		});

	}

	protected void installApk(File file) {
		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(file),
				"application/vnd.android.package-archive");
		startActivity(intent);
	}

	private List<Active> mActive = new ArrayList<Active>();
	String m[];

	//判断应用是否在运行 
	private boolean isRun() {
		ActivityManager am = (ActivityManager)getApplication().getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> list = am.getRunningTasks(100);
		boolean isAppRunning = false;
		String MY_PKG_NAME = "com.anosine.gpsl.android";
		for (RunningTaskInfo info : list) {
			if (info.topActivity.getPackageName().equals(MY_PKG_NAME) || info.baseActivity.getPackageName().equals(MY_PKG_NAME)) {
				isAppRunning = true;
				break;
			}
		}
		return isAppRunning;
	}
	
	@Override
	public void setActiveList(final ActiveList t) {
		int number = 0;
		m = new String[t.list.size()];
		if (t != null) {
			if (GPSLApp.mActive.size() > 0) {
				GPSLApp.mActive = null;
				GPSLApp.mActive = new ArrayList<Active>();
			}
			number = t.list != null ? t.list.size() : 0;
			if (number > 0) {
				for (int i = 0; i < number; i++) {
					mActive.add(t.list.get(i));
					m[i] = t.list.get(i).hn;
					GPSLApp.mActive.add(t.list.get(i));
				}
			}
		}
		Intent intent = getIntent();
		String StringE = intent.getStringExtra("isShowTabMessage");
		if ("ShowTabMessage".equals(StringE)) {
			
			initDataSelectPosition(2);
		} else {
			initDataSelectPosition(0);
		}

//		if (TabMonitoringFragmentNew.isPlayer == 0) {
//		} else if (TabMonitoringFragmentNew.isPlayer == 1) {
//			TabMonitoringFragmentNew.player.stop();
//		}
	    final int screenHeight = getWindowManager().getDefaultDisplay().getHeight();      // 屏幕高（像素，如：800p）  
		if (mActive == null) {
			mBtnView[0].setText("监控");
		} else {
			mBtnView[0].setText(mActive.get(0).hn);
			mBtnView[0].setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					getPopupWindow();
					int[] location = new int[2];
					llheight.getLocationOnScreen(location);// 获得指定控件的坐标					
					popupWindow.showAtLocation(v,
							Gravity.LEFT | Gravity.BOTTOM, 0, screenHeight-location[1]); // y
				}
			});
		}
		// adapter = new ArrayAdapter<String>(this,
		// android.R.layout.simple_spinner_item, m);
		// adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		// mBtnSpinner.setAdapter(adapter);
		// mBtnSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
		// @Override
		// public void onItemSelected(AdapterView<?> parent, View view,
		// int position, long id) {
		// // ////////////其他选项更改/////////////////////////
		// for (int i = 1; i < mBtnView.length; i++) {
		// mBtnView[i].setPressed(false);
		// mBtnView[i].setTextColor(getResources().getColor(
		// R.color.white));
		// mBtnView[i]
		// .setBackgroundResource(R.color.main_head_title_select);
		// switch (i) {
		// case 1:
		// mBtnView[i].setCompoundDrawablesWithIntrinsicBounds(0,
		// R.drawable.main_search_selector, 0, 0);
		// break;
		// case 2:
		// mBtnView[i].setCompoundDrawablesWithIntrinsicBounds(0,
		// R.drawable.main_more_selector, 0, 0);
		// break;
		// case 3:
		// mBtnView[i].setCompoundDrawablesWithIntrinsicBounds(0,
		// R.drawable.main_mine_selector, 0, 0);
		// break;
		// }
		// }
		// // /////////////////////////////////////////////
		// for (int i = mActive.size() - 1; i >= 0; i--) {
		// if (i == position) {
		// GPSLApp.setOid(t.list.get(i).oid);
		// GPSLApp.IsSaveOid = true;
		// // 传值
		// mCurrentShowFrg = new TabMonitoringFragmentNew();
		// FragmentTransaction mTransaction = getSupportFragmentManager()
		// .beginTransaction();
		// mTransaction.setCustomAnimations(
		// R.anim.slide_in_from_left, 0);
		//
		// Bundle bundle = new Bundle();
		// bundle.putString("oid", t.list.get(i).oid);
		// mCurrentShowFrg.setArguments(bundle);
		//
		// mTransaction.replace(R.id.area_show_content,
		// mCurrentShowFrg);
		// mTransaction.commit();
		// break;
		// }
		//
		// }
		//
		// }
		//
		// @Override
		// public void onNothingSelected(AdapterView<?> parent) {
		//
		// }
		// });
	}

	private PopupWindow popupWindow;
	private ListView lv;
	MyAdapter myAdapter;

	/**
	 * 创建PopupWindow
	 */
	protected void initPopuptWindow() {
		// 获取自定义布局文件activity_popupwindow_left.xml的视图
		View pop_view = getLayoutInflater().inflate(
				R.layout.activity_popupwindow, null, false);
		lv = (ListView) pop_view.findViewById(R.id.lv);
		myAdapter = new MyAdapter(this);
		lv.setAdapter(myAdapter);
		DisplayMetrics metric = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metric);
		int width = metric.widthPixels; // 屏幕宽度（像素）
		// 创建PopupWindow实例,200,LayoutParams.MATCH_PARENT分别是宽度和高度
		popupWindow = new PopupWindow(pop_view, width / 4,
				LayoutParams.WRAP_CONTENT, true);
		// 设置动画效果
		// popupWindow.setAnimationStyle(R.style.AnimationFade);
		// 点击其他地方消失
		pop_view.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (popupWindow != null && popupWindow.isShowing()) {
					popupWindow.dismiss();
					popupWindow = null;
				}
				return false;
			}
		});
	}

	/***
	 * 获取PopupWindow实例
	 */
	private void getPopupWindow() {
		if (null != popupWindow) {
			popupWindow.dismiss();
			return;
		} else {
			initPopuptWindow();
		}
	}

	public class MyAdapter extends BaseAdapter

	{

		private LayoutInflater mInflater;

		public MyAdapter(Context context)

		{

			this.mInflater = LayoutInflater.from(context);

		}

		@Override
		public int getCount() {

			return mActive.size();

		}

		@Override
		public Object getItem(int arg0) {

			return mActive.get(arg0);

		}

		@Override
		public long getItemId(int arg0) {

			return 0;

		}

		@Override
		public View getView(final int position, View view, ViewGroup parent) {

			ViewHolder holder = null;

			if (view == null) {
				holder = new ViewHolder();
				view = mInflater.inflate(R.layout.activity_pop_lv_item, null);
				holder.name = (TextView) view.findViewById(R.id.name);
				view.setTag(holder);
			} else {
				holder = (ViewHolder) view.getTag();
			}

			holder.name.setText((String) mActive.get(position).hn);
			holder.name.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					if (popupWindow != null && popupWindow.isShowing()) {
						popupWindow.dismiss();
						popupWindow = null;
					}
					///////////////其他选项更改/////////////////////////
					for (int i = 1; i < mBtnView.length; i++) {
						mBtnView[i].setPressed(false);
						mBtnView[i].setTextColor(getResources().getColor(
								R.color.white));
						mBtnView[i]
								.setBackgroundResource(R.color.main_head_title_select);
						switch (i) {
						case 1:
							mBtnView[i]
									.setCompoundDrawablesWithIntrinsicBounds(0,
											R.drawable.main_search_selector, 0,
											0);
							break;
						case 2:
							mBtnView[i]
									.setCompoundDrawablesWithIntrinsicBounds(0,
											R.drawable.main_more_selector, 0, 0);
							break;
						case 3:
							mBtnView[i]
									.setCompoundDrawablesWithIntrinsicBounds(0,
											R.drawable.main_mine_selector, 0, 0);
							break;
						}
					}
					// /////////////////////////////////////////////
					mBtnView[0].setText(mActive.get(position).hn);
					for (int i = mActive.size() - 1; i >= 0; i--) {
						if (i == position) {
							Login userInfo = UserInfoProxy.getInstance()
									.getLoginInfo();
							userInfo.SaveOid = (mActive.get(i).oid);
							UserInfoProxy.getInstance().setLoginUserInfo(
									userInfo);
							GPSLApp.setOid(mActive.get(i).oid);
							//////很重要////////
							mSelectPosition=0;
							// 传值
							mCurrentShowFrg = new TabMonitoringFragmentNew();
							FragmentTransaction mTransaction = getSupportFragmentManager()
									.beginTransaction();
							mTransaction.setCustomAnimations(
									R.anim.slide_in_from_left, 0);
							Bundle bundle = new Bundle();
							bundle.putString("oid", mActive.get(i).oid);
							mCurrentShowFrg.setArguments(bundle);
							mTransaction.replace(R.id.area_show_content,
									mCurrentShowFrg);
							mTransaction.commit();
							break;
						}
					}
				}
			});
			return view;
		}

		public class ViewHolder {
			TextView name;
		}
	}
}
